# -*- coding:utf-8 -*-
# 该代码包含了两个烟雾传感器的处理
import RPi.GPIO as GPIO
import serial
import time
import csv
import struct
import requests
import json
from requests import exceptions
import redis

url = "http://192.168.195.1:7550/api/fog"
headers = {
  'Content-Type': 'application/json'
}
REDIS_CONFIG = {
    'host': 'localhost',  # IP
    'port': 6379,  # 端口
    'password': '',  # 密码
    'db': 0,  # 数据库
    'decode_responses': True # 将存入的数据进行解码（主要用于将bytes类型转成string类型）
}
r = redis.StrictRedis(**REDIS_CONFIG)
ser1 = serial.Serial("/dev/ttyUSB2", 9600, timeout=0.01)  # receive data once every 0.1S 
ser1.flushInput()

ser2 = serial.Serial("/dev/ttyUSB3", 9600, timeout=0.01)  # receive data once every 0.1S 
ser2.flushInput()

data1 = ""
data2 = ""

send_status1 = True
send_status2 = True

data_count1 = 0 #redis计数
data_count2 = 0

redis_data1 = [] #redis数据
redis_data2 = []

for i in range(120): #初始化
    redis_data2.append({"fog": str(0),"type":7})

V1= 0.0 # A0电压值（损失了低2位精度）
V2= 0.0 # A0电压值（损失了低2位精度）

pmm1 = 0.0
pmm2 = 0.0

f = "./lucky.csv"
line = 0
connect_flag = 1
recover_flag = 0
feedback = struct.pack("BBB",0xaa,0x55,0x01)

print("You can always receive data, press Ctrl + C to exit")
while 1: 
    ser2.flush()
    if ser2.inWaiting() > 0: 
        data2 = ser2.readline()
        if data2 != "":
            if data2[0]==170 and data2[1]==85 and data2[2]==7:
                ser2.write(feedback)
                #树莓派宕机
                if data2[3]==1:
                    fog2 = []
                    for i in range(3,len(data2),4):
                        V2 = 5.0*(data2[i]*4.0)/1024.0  #实际的电压值
                        pmm2 = pow(11.5428 * 35.904 * V2/(25.5-5.1* V2),0.6549) #换算后的浓度值 
                        fog2.append({"fog": str(pmm2)})
                    #发送历史数据
                    payload = json.dumps({"value": fog2,"type":7})
                    try:
                        response = requests.request("POST", url, headers=headers, data=payload,timeout=1)
                    except requests.exceptions.RequestException:
                        print("Error")
                if data2[3]==0:
                # 收到一次烟雾的值就给一个反馈：aa 55 1
                    if data_count2==120:
                        data_count2 = 0
                    
                    V2 = 5.0*(data2[4]*4.0)/1024.0  #实际的电压值
                    pmm2 = pow(11.5428 * 35.904 * V2/(25.5-5.1* V2),0.6549) #换算后的浓度值 
                    #发送实时数据
                    payload = json.dumps({"value": [{"fog": str(pmm2),"type":7}]})
                    print(payload)
                    #redis缓存存储
                    redis_data2[data_count2]={"fog": str(pmm2),"type":7}
                    old_data2 = json.dumps({"value": redis_data2})
                    r.set("fog2", old_data2) 
                    data_count2+=1
                    print(data_count2)
                    try:
                        response = requests.request("POST", url, headers=headers, data=payload,timeout=1.5)
                        print(response.text)
                    except requests.exceptions.RequestException as e:
                        while 1:
                            try:
                                response = requests.request("POST", url, headers=headers, data=r.get("fog2"),timeout=2)
                            except exceptions.Timeout or requests.exceptions.ConnectionError:
                                break
                            except exceptions.HTTPError:
                                pass

                        
                            
